﻿using System;
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace xhim.client.update.console
{
    public partial class FrmControl : Form
    {
        public FrmControl()
        {
            InitializeComponent();
            btnInstall.Click += btnInstall_Click;
            btnStart.Click += btnStart_Click;
            btnStop.Click += btnStop_Click;
            btnUninstall.Click += btnUninstall_Click;
            timer1.Tick += timer1_Tick;
            this.Load += Form1_Load;
        }


        string serviceFilePath = $"{Application.StartupPath}/xhim-client-update-service.exe";
        string serviceName = "XhimClientUpdateService";

        private void btnInstall_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                ShowMessage("开始安装服务...");
                if (IsServiceExisted(serviceName))
                {
                    UninstallService(serviceFilePath);
                }
                InstallService(serviceFilePath);
            });
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                ShowMessage("服务正在启动...");
                if (IsServiceExisted(serviceName))
                {
                    ServiceStart(serviceName);
                    ShowMessage("服务已启动");
                }

            });
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                ShowMessage("服务正在停止...");
                if (IsServiceExisted(serviceName))
                {
                    ServiceStop(serviceName);
                    ShowMessage("服务已停止");
                }
            });
        }



        private void btnUninstall_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                ShowMessage("开始卸载服务...");
                if (this.IsServiceExisted(serviceName))
                {
                    this.ServiceStop(serviceName);
                }
                this.UninstallService(serviceFilePath);
            });
        }

        #region 方法封装
        private void ShowMessage(string s)
        {
            Action setState = () =>
            {
                myTxtBox.AppendText(DateTime.Now.ToString("f") + "：");
                myTxtBox.AppendText(Environment.NewLine);
                myTxtBox.AppendText(s);
                myTxtBox.AppendText(Environment.NewLine);

            };
            myTxtBox.Invoke(setState);
        }

        //判断服务是否存在
        private bool IsServiceExisted(string serviceName)
        {
            try
            {
                ServiceController[] services = ServiceController.GetServices();
                foreach (ServiceController sc in services)
                {
                    if (sc.ServiceName.ToLower() == serviceName.ToLower())
                    {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
                return false;
            }
        }

        //安装服务
        private void InstallService(string serviceFilePath)
        {
            try
            {
                using (AssemblyInstaller installer = new AssemblyInstaller())
                {
                    installer.UseNewContext = true;
                    installer.Path = serviceFilePath;
                    IDictionary savedState = new Hashtable();
                    installer.Install(savedState);
                    installer.Commit(savedState);
                    ShowMessage("服务安装完成");
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        //卸载服务
        private void UninstallService(string serviceFilePath)
        {
            try
            {
                using (AssemblyInstaller installer = new AssemblyInstaller())
                {
                    installer.UseNewContext = true;
                    installer.Path = serviceFilePath;
                    installer.Uninstall(null);
                    ShowMessage("服务卸载完成");
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        //启动服务
        private void ServiceStart(string serviceName)
        {
            try
            {
                using (ServiceController control = new ServiceController(serviceName))
                {
                    if (control.Status == ServiceControllerStatus.Stopped)
                    {
                        control.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }


        //停止服务
        private void ServiceStop(string serviceName)
        {
            try
            {
                using (ServiceController control = new ServiceController(serviceName))
                {
                    if (control.Status == ServiceControllerStatus.Running)
                    {
                        control.Stop();
                    }
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }
        #endregion

        #region 页面元素

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;

            timer1.Interval = 100;
            timer1.Enabled = true;
        }

        //btn状态
        private void ButtonState()
        {
            if (IsServiceExisted(serviceName))
            {
                btnInstall.Enabled = false;
                btnUninstall.Enabled = true;
                using (var service = new ServiceController(serviceName))
                {
                    if (service.Status == ServiceControllerStatus.Running || service.Status == ServiceControllerStatus.StartPending)
                    {
                        btnUninstall.Enabled = false;
                        btnStart.Enabled = false;
                        btnStop.Enabled = true;
                    }
                    else
                    {
                        btnUninstall.Enabled = true;
                        btnStart.Enabled = true;
                        btnStop.Enabled = false;
                    }
                }
            }
            else
            {
                btnInstall.Enabled = true;
                btnUninstall.Enabled = false;
                btnStart.Enabled = false;
                btnStop.Enabled = false;
            }
        }
        //底部label状态
        private void LabelState()
        {
            if (!IsServiceExisted(serviceName))
            {
                this.labState.Text = $"【{serviceName}】服务未安装";
                return;
            }
            using (var service = new ServiceController(serviceName))
            {
                switch (service.Status)
                {
                    case ServiceControllerStatus.Running:
                        this.labState.Text = $"【{serviceName}】服务已启动";
                        break;
                    case ServiceControllerStatus.StartPending:
                        this.labState.Text = $"【{serviceName}】服务正在启动...";
                        break;
                    case ServiceControllerStatus.Stopped:
                        this.labState.Text = $"【{serviceName}】服务已停止";
                        break;
                    case ServiceControllerStatus.StopPending:
                        this.labState.Text = $"【{serviceName}】服务正在停止...";
                        break;
                    default:
                        break;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ButtonState();
            LabelState();
        }
        #endregion
    }
}
